package com.zjm.behavioral.observer.demo02;

import java.util.ArrayList;
import java.util.List;

/**
 * 包含最新的天气信息
 * 包含观察者集合，使用ArrayList管理
 * 当数据更新时，通知所有的接入方，获取最新数据
 */
public class WeatherData implements Subject {
    private float temperature;
    private float pressure;
    private float humidity;

    // 观察者集合
    private List<Observer> observers;

    public WeatherData() {
        observers = new ArrayList<>();
    }

    public float getTemperature() {
        return temperature;
    }

    public float getPressure() {
        return pressure;
    }

    public float getHumidity() {
        return humidity;
    }

    public void dataChange() {
        notifyObservers();
    }

    /**
     * 数据更新时调用
     *
     * @param temperature
     * @param pressure
     * @param humidity
     */
    public void setData(float temperature, float pressure, float humidity) {
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        // 调用dataChange()，将最新信息推送给接入方currentConditions
        dataChange();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        if (observers.contains(observer)) {
            observers.remove(observer);
        }
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(this.temperature, this.pressure, this.humidity);
        }
    }
}
